<template>
  <uni-popup ref="popup" type="bottom" @maskClick="close">
    <view class="region-picker">
      <view class="picker-header">
        <text class="btn-cancel" @click="close">取消</text>
        <text class="title">选择地区</text>
        <text class="btn-confirm" @click="confirm">确定</text>
      </view>

      <picker-view
        class="picker-view"
        :value="pickerValue"
        @change="handleChange"
        @pickstart="onPickStart"
        @pickend="onPickEnd"
      >
        <picker-view-column>
          <view
            class="picker-item"
            v-for="(province, index) in regions"
            :key="province.code"
            :data-index="index"
          >
            {{ province.name }}
          </view>
        </picker-view-column>

        <picker-view-column>
          <view
            class="picker-item"
            v-for="(city, index) in currentCities"
            :key="city.code"
            :data-index="index"
          >
            {{ city.name }}
          </view>
        </picker-view-column>

        <picker-view-column>
          <view
            class="picker-item"
            v-for="(district, index) in currentDistricts"
            :key="district.code"
            :data-index="index"
          >
            {{ district.name }}
          </view>
        </picker-view-column>
      </picker-view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, computed, watch, nextTick } from "vue";
import regionData from "@/data/region.json";

const props = defineProps({
  modelValue: Boolean,
});

const emit = defineEmits(["update:modelValue", "confirm"]);

const popup = ref(null);
const pickerValue = ref([0, 0, 0]);

// 暴露打开方法
const open = () => {
  popup.value.open();
};

const normalizeData = () => {
  return Object.values(regionData).map((province) => ({
    code: province.code,
    name: province.name,
    children: province.children ? Object.values(province.children) : [],
  }));
};

const regions = ref(normalizeData());

// 当前选中的省市区计算属性
const currentProvince = computed(() => {
  return regions.value[pickerValue.value[0]] || {};
});

const currentCities = computed(() => {
  return currentProvince.value.children || [];
});

const currentDistricts = computed(() => {
  const cityIndex = pickerValue.value[1];
  return currentCities.value[cityIndex]?.children || [];
});

// 处理picker变化
const handleChange = (e) => {
  const value = e.detail.value;

  // 如果省份变化，重置城市和区县
  if (value[0] !== pickerValue.value[0]) {
    value[1] = 0;
    value[2] = 0;
  }
  // 如果城市变化，重置区县
  else if (value[1] !== pickerValue.value[1]) {
    value[2] = 0;
  }

  pickerValue.value = value;
};

// 确认选择
const confirm = () => {
  const province = currentProvince.value;
  const city = currentCities.value[pickerValue.value[1]] || {};
  let keys = Object.keys(currentDistricts.value).sort();
  let fourthKey = keys[pickerValue.value[2]]; // 假设数组索引从0开始，第四个元素的索引是3
  const district = currentDistricts.value[fourthKey] || {};
  emit("confirm", [
    { name: province.name, code: province.code },
    { name: city.name, code: city.code },
    { name: district.name , code: district.code },
  ]);
  close();
};

// 关闭弹窗
const close = () => {
  emit("update:modelValue", false);
  popup.value.close();
};

// 监听显示状态
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      nextTick(() => {
        popup.value.open();
      });
    } else {
      popup.value.close();
    }
  }
);

// 暴露方法
defineExpose({
  open,
  close,
});
</script>

<style lang="scss">
.region-picker {
  background-color: $white-bg;;
  border-radius: 20rpx 20rpx 0 0;

  .picker-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #f5f5f5;

    .btn-cancel,
    .btn-confirm {
      font-size: $font-size-28rpx;
      color: $text-color-666;
    }

    .btn-confirm {
      color: $primary-color;
    }

    .title {
      font-size: $font-size-30rpx;
      font-weight: bold;
    }
  }

  .picker-view {
    height: 400rpx; /* 固定高度，避免动态计算 */

    /* 每列单独设置样式 */
    picker-view-column {
      view {
        height: 59.5rpx; /* 固定行高 */
        line-height: 59.5rpx; /* 行高与高度一致 */
        font-size: $font-size-30rpx;
        text-align: center;
        @include text-ellipsis(1); /* 确保单行显示 */

        /* 选中项样式 */
        &.selected {
          color: $primary-color;
          font-weight: bold;
        }
      }
    }

    /* 指示器样式 */
    &::after {
      content: "";
      position: absolute;
      left: 0;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      height: 80rpx;
      border-top: 1rpx solid #eee;
      border-bottom: 1rpx solid #eee;
      pointer-events: none;
    }
  }
}
</style>
